package org.idea.qiyu.threadpool.demo.asynchandle;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @Author linhao
 * @Date created in 5:05 下午 2021/10/17
 */
@Component("asyncSingleConsumerHandler")
public class AsyncSingleConsumerHandler implements AsyncHandlerService{

    private volatile SingleTaskQueueHandler taskQueueHandler = new SingleTaskQueueHandler();

    @Override
    public boolean putTask(AsyncHandlerData asyncHandlerData) {
        return taskQueueHandler.addTask(asyncHandlerData);
    }

    @Override
    public void startJob() {
        Thread thread = new Thread(taskQueueHandler);
        thread.setDaemon(true);
        thread.start();
    }

    static class SingleTaskQueueHandler implements Runnable {

        /**
         * 整体的性能吞吐能力取决于堵塞队列的大小
         */
        private static BlockingQueue<AsyncHandlerData> tasks = new ArrayBlockingQueue<>(11);

        public static BlockingQueue<AsyncHandlerData> getAllTaskInfo() {
            return tasks;
        }

        public boolean addTask(AsyncHandlerData asyncHandlerData) {
            return tasks.offer(asyncHandlerData);
        }

        @Override
        public void run() {
            for (; ; ) {
                try {
                    tasks.take();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
